from ChanPin.models import Dingdan,Chanpin,ChanpinLeibie
import datetime
import random
from django.contrib.auth.models import User
from django import forms
from django.forms import ModelForm

from django.forms.models import ModelMultipleChoiceField

###2024/10/15 客户详情页生成订单新增功能###

class CustomModelChoiceField(forms.ModelChoiceField):
    """自定义ModelChoiceField，用于生成订单页面中的产品选择下拉框"""

    def label_from_instance(self, obj):
        # 假设 if_xiaolei 是一个包含 choices 的字段
        if_xiaolei_display = dict(obj.get_if_xiaolei_display()).get(obj.if_xiaolei, 'Unknown')
        return f"{obj.name} - {if_xiaolei_display}"
    # def __init__(self, *args, label_from_instance=None, **kwargs):
    #     super().__init__(*args, **kwargs)
    #     self.label_from_instance = label_from_instance
    #
    # def label_from_instance(self, obj):
    #     if self.label_from_instance is not None:
    #         return self.label_from_instance(obj)
    #     return super().label_from_instance(obj)


def generate_ddh():
    date_part = datetime.datetime.now().strftime('%Y%m%d')
    random_part = '{:05d}'.format(random.randint(0, 99999))
    return f"{date_part}{random_part}"

class KeHuDingdanForm(forms.ModelForm):
    """客户详情页生成的订单表单"""
    ChanpinLeibie_xz = CustomModelChoiceField(
        queryset=ChanpinLeibie.objects.filter(if_xianshi=1),  # 替换为您要关联的模型的查询集
        label='产品类别',
        empty_label='选择产品类别',
        widget=forms.Select(
            attrs={
                'class': 'form-control',
                'id': 'ChanpinLeibie_xz'
            },

        ),
    )
    class Meta:
        model = Dingdan
        fields = ['ddh', 'ddtime', 'ChanpinLeibie_xz', 'ddjine', 'ddchanpin', 'kaipiaoif']
        widgets = {
            'ddtime': forms.DateTimeInput(attrs={'type': 'datetime-local'}),
            #'ddchanpin': forms.SelectMultiple(attrs={'class': 'form-control'},)
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['ddh'].initial = generate_ddh()  # 设置初始值 随机订单号
        self.fields['ddchanpin'].label_from_instance =lambda obj: f"{obj.title}-$({obj.jiage})-{obj.gys}"
        # 为'ChanpinLeibie_xz'字段添加自定义的label_from_instance方法，以便在下拉列表中显示类别名称
        self.fields['ChanpinLeibie_xz'].label_from_instance = lambda obj: f'{obj.name} - {obj.get_if_xiaolei_display()}'
        # # 为所有字段的widget添加'form-control'类，除了已经设置为readonly的'dduser'
        common_attrs = {'class': 'form-control'}
        for field in self.fields:
             self.fields[field].widget.attrs.update(common_attrs)


class ChanpinForm(forms.ModelForm):
    class Meta:
      model = Chanpin
      fields = ['title','jiage','jiage_dijia','leibie','gys','beizhu','fujian']
      widgets = {
          'title': forms.TextInput(attrs={'class': 'form-control'}),
          'jiage': forms.NumberInput(attrs={'class': 'form-control'}),
          'jiage_dijia': forms.NumberInput(attrs={'class': 'form-control'}),
          'leibie': forms.Select(attrs={'class': 'form-control'}),
          'gys': forms.Select(attrs={'class': 'form-control '}),
          'beizhu': forms.Textarea(attrs={'class': 'form-control'}),
          'fujian': forms.ClearableFileInput(attrs={'class': 'form-control'}),
      }
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['leibie'].queryset = ChanpinLeibie.objects.filter(if_xianshi=1)
        self.fields['leibie'].label_from_instance = lambda obj: obj.get_xiaolei_display() +"-"f'{obj.name}' # 使用新添加的方法来获取显示名称

